/* eslint-disable import/no-anonymous-default-export */
/* eslint-disable jsx-a11y/anchor-is-valid */

import "./style.scss";
import React, { useState, useContext, useEffect, useMemo } from "react";
import { useNavigate, useLocation } from "react-router";
import {
  Button,
  message,
  Spin,
  Cascader,
  Checkbox,
  Input,
  Select,
  Row,
  Col,
} from "antd";
import AiLogo from "../../assets/img/aipin-logo.png";

import cityOptions from "../../components/DivisionsOfZhong/index";
import { postJob } from "../../api/jobpost";
import { getJobList } from "../../api/joblist";
import { UserContext } from "../../store/user";

// console.log('cityOptions: ', cityOptions)
const { TextArea } = Input;

export default () => {
  const [messageApi] = message.useMessage();
  const [loading, setLoading] = useState(false);

  const navigate = useNavigate();
  const ctx = useContext(UserContext);
  // console.log('ctx=', ctx)
  const user = ctx.user;
  const location = useLocation();
  const paramId = location.pathname.replace(/\/jobpost\/?/, "");
  console.log('当前职位发布页面参数: ', location.pathname)
  const [isEdit, setIsEdit] = useState(false); // 是否是编辑状态

  // 职位名称
  const [jobTitle, setJobTitle] = useState("");
  // 职位类别
  const [jobCategory, setJobCategory] = useState(null);
  // 工作地点
  const [jobLocation, setJobLocation] = useState(null);
  // 是否远程
  const [isRemoted, setIsRemoted] = useState(false);
  // 薪资范围
  const [minSalary, setMinSalary] = useState();
  const [maxSalary, setMaxSalary] = useState();
  // 经验要求
  const [experienceRequirement, setExperienceRequirement] = useState("");
  // 学历要求
  const [educationRequirement, setEducationRequirement] = useState("");
  // 职位描述
  const [jobDescription, setJobDescription] = useState("");
  // 岗位职责
  const [jobResponsibilities, setJobResponsibilities] = useState("");
  // 任职要求
  const [jobRequirement, setJobRequirement] = useState("");
  // 福利待遇

  const canSubmit = () => {
    if (jobTitle && jobCategory && jobLocation && jobDescription) {
      return false;
    }
    return true;
  };

  useEffect(() => {
    // 如果页面有id, 根据id取表单数据
    if (paramId) {
      (async () => {
        let res = await getJobList({ id: paramId });
        console.log("职位数据: ", res.result);
        if (res.result) {
          setJobTitle(res.result.jobTitle);
          setJobCategory(res.result.jobCategory);
          setJobLocation(res.result.jobLocation ? res.result.jobLocation.split(','):[]);
          setMinSalary(res.result.minSalary);
          setMaxSalary(res.result.maxSalary);
          setExperienceRequirement(res.result.experienceRequirement);
          setEducationRequirement(res.result.educationRequirement);
          setJobDescription(res.result.jobDescription);
          setJobResponsibilities(res.result.jobResponsibilities);
          setJobRequirement(res.result.jobRequirement);
          setIsRemoted(Boolean(res.result.isRemoted));
        }

        // 确定是否是编辑状态
        if (sessionStorage["recruite-edit"]) {
          delete sessionStorage["recruite-edit"];
          setIsEdit(true);
        }
      })();
    }
  }, []);

  const isDisabled = useMemo(() => {
    if (paramId) {
      if (isEdit) {
        return false;
      }
      return true;
    } else {
      return false;
    }
  }, [isEdit]);

  return (
    <div className="bg-gray-50 text-gray-800 job-post-page">
      <Spin spinning={loading}>
        <header className="bg-white shadow-sm">
          <div className="container mx-auto px-4 py-4 flex items-center justify-between">
            <div className="flex items-center">
              <img className="block" src={AiLogo} alt="" width="100" />
              <div className="ml-10 hidden md:flex space-x-6">
                <a href="#" className="text-gray-600 hover:text-primary">
                  首页
                </a>
                <a href="#" className="text-primary font-medium">
                  职位管理
                </a>
                <a href="#" className="text-gray-600 hover:text-primary">
                  人才库
                </a>
                <a href="#" className="text-gray-600 hover:text-primary">
                  消息中心
                </a>
              </div>
            </div>
            <div className="flex items-center space-x-4">
              {/* <div className="w-10 h-10 flex items-center justify-center text-gray-600 hover:text-primary cursor-pointer">
              <i className="ri-notification-3-line ri-lg"></i>
            </div> */}
              <div className="flex items-center space-x-2">
                {/* <div className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center">
                  <span className="text-sm">张</span>
                </div> */}
                <span className="hidden md:inline">{user.loginBizId}</span>
              </div>
            </div>
          </div>
        </header>

        <main className="container mx-auto px-4 py-8 max-w-3xl">
          <div className="mb-8">
            <h1 className="text-3xl font-bold mb-2">发布新职位</h1>
            <p className="text-gray-600">填写职位信息，寻找合适人才</p>
          </div>

          <div className="mb-6">
            <div className="progress-bar">
              <div
                className="progress-value"
                id="formProgress"
                style={{ width: 0 }}
              ></div>
            </div>
            <div className="flex justify-between mt-2 text-sm text-gray-500">
              <span>填写进度</span>
              <span id="progressText">0%</span>
            </div>
          </div>

          <form
            id="jobPostForm"
            className="bg-white rounded-lg shadow-sm p-6 mb-8"
          >
            <div className="space-y-6">
              <div>
                <label htmlFor="jobTitle" className="form-label required">
                  职位名称
                </label>
                <Input
                  placeholder="例如：高级前端工程师"
                  value={jobTitle}
                  onChange={(e) => {
                    setJobTitle(e.target.value);
                  }}
                  disabled={isDisabled}
                  size="large"
                  showCount
                  maxLength={50}
                />
                <p className="mt-1 text-sm text-gray-500 flex justify-between">
                  <span>职位名称是求职者搜索的重要依据</span>
                </p>
              </div>

              <div>
                <label htmlFor="jobCategory" className="form-label required">
                  职位类别
                </label>
                <div className="custom-select" id="jobCategorySelect">
                  <Select
                    size="large"
                    disabled={isDisabled}
                    allowClear={true}
                    placeholder="请选择"
                    value={jobCategory}
                    onChange={(val) => {
                      setJobCategory(val);
                    }}
                    style={{ width: "100%" }}
                    options={[
                      { value: "技术", label: "技术" },
                      { value: "产品", label: "产品" },
                      { value: "设计", label: "设计" },
                      { value: "运营", label: "运营" },
                      { value: "市场", label: "市场" },
                      { value: "销售", label: "销售" },
                      { value: "财务", label: "财务" },
                      { value: "人力资源", label: "人力资源" },
                      { value: "行政", label: "行政" },
                      { value: "法务", label: "法务" },
                      { value: "其他", label: "其他" },
                    ]}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="jobLocation" className="form-label required">
                  工作地点
                </label>
                <div className="flex gap-4">
                  <Cascader
                    disabled={isDisabled}
                    options={cityOptions}
                    value={jobLocation}
                    onChange={(val) => {
                      // console.log("===>", val);
                      setJobLocation(val);
                    }}
                    placeholder="请选择工作地点"
                    style={{ width: "100%" }}
                    size="large"
                  />
                </div>
                <div className="mt-3">
                  <label className="inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      id="remoteWork"
                      disabled={isDisabled}
                      className="sr-only peer"
                      checked={isRemoted}
                      onChange={(e) => {
                        // console.log('====>', e.target.checked)
                        setIsRemoted(e.target.checked);
                      }}
                    />
                    <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                    <span className="ms-3 text-sm font-medium text-gray-700">
                      支持远程工作
                    </span>
                  </label>
                </div>
              </div>
              <div>
                <label className="form-label required">
                  薪资范围（单位：千元/月）
                </label>
                <div className="custom-range">
                  <input
                    disabled={isDisabled}
                    type="number"
                    id="salaryMin"
                    className="form-input custom-range-input"
                    placeholder="最低"
                    min="1"
                    required
                    value={minSalary}
                    onChange={(e) => {
                      setMinSalary(e.target.value);
                    }}
                  />
                  <span className="custom-range-separator">-</span>
                  <input
                    type="number"
                    disabled={isDisabled}
                    id="salaryMax"
                    className="form-input custom-range-input"
                    placeholder="最高"
                    min="1"
                    required
                    value={maxSalary}
                    onChange={(e) => {
                      setMaxSalary(e.target.value);
                    }}
                  />
                </div>
                <div className="mt-3">
                  <label className="inline-flex items-center cursor-pointer">
                    <input
                      disabled={isDisabled}
                      type="checkbox"
                      id="salaryNegotiable"
                      className="sr-only peer"
                    />
                    <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                    <span className="ms-3 text-sm font-medium text-gray-700">
                      薪资可面议
                    </span>
                  </label>
                </div>
              </div>

              <div>
                <label htmlFor="experience" className="form-label">
                  经验要求
                </label>
                <div className="custom-select" id="experienceSelect">
                  <Select
                    size="large"
                    disabled={isDisabled}
                    allowClear={true}
                    placeholder="请选择经验要求"
                    style={{ width: "100%" }}
                    value={experienceRequirement}
                    onChange={(val) => {
                      setExperienceRequirement(val);
                    }}
                    options={[
                      { value: "不限", label: "不限" },
                      { value: "应届毕业生", label: "应届毕业生" },
                      { value: "1年以下", label: "1年以下" },
                      { value: "1-3年", label: "1-3年" },
                      { value: "3-5年", label: "3-5年" },
                      { value: "5-10年", label: "5-10年" },
                      { value: "财务", label: "财务" },
                      { value: "人力资源", label: "人力资源" },
                      { value: "10年以上", label: "10年以上" },
                    ]}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="education" className="form-label">
                  学历要求
                </label>
                <div className="custom-select" id="educationSelect">
                  <Select
                    disabled={isDisabled}
                    size="large"
                    allowClear={true}
                    placeholder="请选择学历要求"
                    style={{ width: "100%" }}
                    value={educationRequirement}
                    onChange={(val) => {
                      setEducationRequirement(val);
                    }}
                    options={[
                      { value: "不限", label: "不限" },
                      { value: "高中", label: "高中" },
                      { value: "大专", label: "大专" },
                      { value: "本科", label: "本科" },
                      { value: "硕士", label: "硕士" },
                      { value: "博士", label: "博士" },
                    ]}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="jobDescription" className="form-label required">
                  职位描述
                </label>
                <div>
                  <TextArea
                    disabled={isDisabled}
                    showCount
                    maxLength={2000}
                    placeholder="请详细描述该职位的工作内容、职责等信息"
                    style={{ height: 120 }}
                    value={jobDescription}
                    onChange={(e) => {
                      setJobDescription(e.target.value);
                    }}
                  />
                </div>
                <p className="mt-1 text-sm text-gray-500 flex justify-between">
                  <span>详细的职位描述有助于吸引合适的求职者</span>
                  {/* <span id="jobDescriptionCount">0/2000</span> */}
                </p>
              </div>

              <div>
                <label htmlFor="jobResponsibilities" className="form-label">
                  岗位职责
                </label>
                <TextArea
                  disabled={isDisabled}
                  showCount
                  maxLength={1000}
                  placeholder="请请列出该岗位的主要职责和工作内容"
                  style={{ height: 120 }}
                  value={jobResponsibilities}
                  onChange={(e) => {
                    setJobResponsibilities(e.target.value);
                  }}
                />
                <p className="mt-1 text-sm text-gray-500 flex justify-between">
                  <span>建议使用要点列表形式</span>
                  {/* <span id="jobResponsibilitiesCount">0/1000</span> */}
                </p>
              </div>

              <div>
                <label htmlFor="jobRequirements" className="form-label">
                  任职要求
                </label>
                <TextArea
                  disabled={isDisabled}
                  showCount
                  maxLength={1000}
                  placeholder="请列出应聘者需要具备的技能、经验和素质"
                  style={{ height: 120 }}
                  value={jobRequirement}
                  onChange={(e) => {
                    setJobRequirement(e.target.value);
                  }}
                />
                <p className="mt-1 text-sm text-gray-500 flex justify-between">
                  <span>明确的要求有助于筛选合适的候选人</span>
                  {/* <span id="jobRequirementsCount">0/1000</span> */}
                </p>
              </div>

              <div>
                <label className="form-label">福利待遇</label>
                <div className="mt-2">
                  <Checkbox.Group>
                    <Row>
                      <Col span={6}>
                        <Checkbox value="五险一金">五险一金</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="年终奖">年终奖</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="带薪年假">带薪年假</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="绩效奖金">绩效奖金</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="定期体检">定期体检</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="节日福利">节日福利</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="餐补">餐补</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="交通补助">交通补助</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="通讯补贴">通讯补贴</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="专业培训">专业培训</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="弹性工作">弹性工作</Checkbox>
                      </Col>
                      <Col span={6}>
                        <Checkbox value="团队建设">团队建设</Checkbox>
                      </Col>
                    </Row>
                  </Checkbox.Group>
                </div>
              </div>
            </div>
          </form>

          <div className="sticky bottom-0 bg-white p-4 border-t border-gray-200 flex justify-between">
            <div>
              <button
                type="button"
                id="previewBtn"
                className="px-5 py-2 border border-gray-300 rounded-button text-gray-700 hover:bg-gray-50 whitespace-nowrap mr-3"
              >
                预览
              </button>
              <button
                type="button"
                id="saveAsDraftBtn"
                className="px-5 py-2 border border-gray-300 rounded-button text-gray-700 hover:bg-gray-50 whitespace-nowrap"
              >
                保存草稿
              </button>
            </div>
            {!isDisabled ? (
              <Button
                type="primary"
                form="jobPostForm"
                disabled={canSubmit()}
                onClick={() => {
                  (async () => {
                    if (!paramId) {
                      // 新增
                      setLoading(true);
                      await postJob([
                        {
                          loginBizId: user.loginBizId,
                          jobTitle,
                          jobCategory,
                          jobLocation: jobLocation.join(","),
                          isRemoted: isRemoted ? 1 : 0,
                          minSalary,
                          maxSalary,
                          experienceRequirement,
                          educationRequirement,
                          jobDescription,
                          jobResponsibilities,
                          jobRequirement,
                        },
                      ]);
                      messageApi.open({
                        type: "success",
                        content: "职位发布成功",
                      });

                      setTimeout(() => {
                        sessionStorage["pub-sucess"] = 1;
                        navigate(-1);
                      }, 1000);
                      setLoading(false);
                    } else {
                      // 编辑
                      setLoading(true);
                      await postJob([
                        {
                          id: paramId,
                          loginBizId: user.loginBizId,
                          jobTitle,
                          jobCategory,
                          jobLocation: jobLocation.join(","),
                          isRemoted: isRemoted ? 1 : 0,
                          minSalary,
                          maxSalary,
                          experienceRequirement,
                          educationRequirement,
                          jobDescription,
                          jobResponsibilities,
                          jobRequirement,
                        },
                      ]);
                      messageApi.open({
                        type: "success",
                        content: "职位发布成功",
                      });

                      setTimeout(() => {
                        sessionStorage["pub-sucess"] = 1;
                        sessionStorage["recruite-view"] = 'return'
                        navigate(-1);
                      }, 1000);
                      setLoading(false);
                    }
                  })();
                }}
                className="px-6 py-2 bg-primary text-white rounded-button whitespace-nowrap"
              >
                发布职位
              </Button>
            ) : (
              <>
                <Button
                  onClick={() => {
                    sessionStorage["recruite-view"] = "return";
                    navigate(-1);
                  }}
                >
                  返回
                </Button>
              </>
            )}
          </div>
        </main>

        <div
          id="autoSaveToast"
          className="fixed bottom-4 right-4 bg-gray-800 text-white px-4 py-2 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center"
        >
          <i className="ri-check-line mr-2"></i>
          <span>已自动保存</span>
        </div>
      </Spin>
    </div>
  );
};
